import 'dart:io';

import 'package:flutter/material.dart';
import 'package:xindong/common/xindong_sezhi.dart';
import 'package:xindong/res/assets_res.dart';
import 'package:xindong/utils/xindong_image_util.dart';

// 上传头像视图
class XinDongAvatarUploadWidget extends StatelessWidget {
  final File? avatarFile;
  final String? avatarUrl;
  final Function(File) callBack;

  // 构造函数
  const XinDongAvatarUploadWidget({Key? key, this.avatarFile, this.avatarUrl, required this.callBack})
      : super(key: key);

  // 选择照片
  void selectedAvatar() async {
    File? file = await ImageUtil.selectAvatar();
    if (file != null) {
      callBack(file);
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).requestFocus(FocusNode()); // 触摸收起键盘
        selectedAvatar();
      },
      behavior: HitTestBehavior.opaque,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 头像
          SizedBox(
            width: 82,
            height: 82,
            child: ClipOval(
              child: _getImage(),
            ),
          ),

          // 上传提示
          const SizedBox(height: 15),
          const Text(
            "上传本人头像",
            style: TextStyle(color: DZColors.contentColor, fontSize: 12),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  // 获取指定图片
  Widget _getImage() {
    if (avatarFile != null) {
      return Image.file(avatarFile!, fit: BoxFit.cover);
    } else if (avatarUrl != null && avatarUrl!.isNotEmpty) {
      return ImageUtil.avatarUrl(avatarUrl!);
    }
    return Container(
      color: DZColors.coverColor,
      alignment: Alignment.center,
      child: ImageUtil.asset(AssetsRes.IMAGE_ADD, width: 30, height: 30),
    );
  }
}
